package com.spark.lola.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spark.lola.constant.SupOrderAction;
import com.spark.lola.constant.SupOrderStatus;
import com.spark.lola.entity.pur.OrderInfo;
import com.spark.lola.entity.pur.OrderProcess;
import com.spark.lola.feign.service.PortalServiceOpenApi;
import com.spark.lola.logistics.entity.Message;
import com.spark.lola.logistics.service.MessageService;
import com.spark.lola.mapper.gds.ProductInfoMapper;
import com.spark.lola.mapper.pur.OrderProductMapper;
import com.spark.lola.mapper.sup.SupplierInfoMapper;
import com.spark.lola.support.common.entity.ShiroUser;
import com.spark.lola.support.common.util.TimeUtil;
import com.spark.lola.support.wms.cache.CollectionCache;
import com.spark.lola.support.wms.configuration.JPushProperties;
import com.spark.lola.support.wms.configuration.WmsProperties;
import com.spark.lola.support.wms.constant.KafkaTopic;
import com.spark.lola.support.wms.constant.WmsNettyCommands;
import com.spark.lola.support.wms.dto.JPushSendDto;
import com.spark.lola.support.wms.dto.OrderDto;
import com.spark.lola.support.wms.util.JPushUtil;
import com.spark.lola.support.wms.vo.NettyOrderMessage;
import com.spark.lola.support.netty.common.NettyCacheUtils;
import com.spark.lola.support.netty.service.HawkPushServiceApi;
import io.netty.channel.Channel;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 采购单消费
 *
 * @Author: DengYeJun
 * @Date: 2020/5/11 18:41
 */
@Component
public class PurOrderConsumer {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private HawkPushServiceApi pushServiceApi;
    @Autowired
    private WmsProperties wmsProperties;
    @Autowired
    private SupplierInfoMapper supplierInfoMapper;
    @Autowired
    private ProductInfoMapper productInfoMapper;
    @Autowired
    private OrderProductMapper orderProductMapper;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    private PortalServiceOpenApi portalServiceOpenApi;

    @Autowired
    private MessageService messageService;

    @Autowired
    private JPushProperties jPushProperties;

    @Autowired
    private JPushUtil jPushUtil;

    @KafkaListener(topics = KafkaTopic.PUR_ORDER_CHANGE)
    @Transactional(rollbackFor = Exception.class)
    public void change(ConsumerRecord<String, String> consumerRecord) throws Exception {
        logger.info("===consumer【PurOrder】采购单【{}】===START===", consumerRecord.key());
        OrderDto<JSONObject> model = JSON.parseObject(consumerRecord.value(), OrderDto.class);
        OrderProcess orderProcess = JSON.parseObject(model.getMessage(), OrderProcess.class);
        OrderInfo orderInfo = JSON.parseObject(model.getOrder().toJSONString(), OrderInfo.class);

        // 拼装通知消息
        NettyOrderMessage message = new NettyOrderMessage();
        message.setOrderId(orderInfo.getId().toString());
        message.setOrderNo(orderInfo.getNo());
        message.setStatus(orderProcess.getAction());
        message.setMessage(orderProcess.getInfo());
        logger.info("===推送消息");
        dealPush(orderInfo, orderProcess, model.getJPushMessage(), message);
        logger.info("===consumer【PurOrder】采购单【{}】===END===", consumerRecord.key());
    }

    @KafkaListener(topics = KafkaTopic.PUR_ORDER_NOTIFICATION)
    @Transactional(rollbackFor = Exception.class)
    public void notification(ConsumerRecord<String, String> consumerRecord) throws Exception {
        OrderInfo model = JSON.parseObject(consumerRecord.value(), OrderInfo.class);
        logger.info("===采购单【{}】加急处理通知===START===", model.getNo());
        // 拼装通知消息
        NettyOrderMessage message = new NettyOrderMessage();
        message.setOrderId(model.getId().toString());
        message.setOrderNo(model.getNo());
        message.setStatus(model.getStatus() + 1);

        List<ShiroUser> shiroUsers = new ArrayList<>();
        switch (model.getStatus()) {
            case SupOrderStatus.WAIT_PRICING:
                // 获取采购主管人员列表
                shiroUsers = filterBySalesman(model.getSalesmanId()
                        , CollectionCache.dutyEmployees.get(wmsProperties.getPurchase().getDutyId().get(0))
                );
                message.setMessage(TimeUtil.getCurrentTime() + "请求【定价】加急处理");
                break;
            case SupOrderStatus.WAIT_ADJUST:
                // 获取采购财务列表
                shiroUsers = filterBySalesman(model.getSalesmanId()
                        , CollectionCache.dutyEmployees.get(wmsProperties.getPurchase().getDutyId().get(3)));
                message.setMessage(TimeUtil.getCurrentTime() + "请求【核算】加急处理");
                break;
            case SupOrderStatus.WAIT_PAYMENT:
                // 获取出纳
                shiroUsers.add(CollectionCache.employees.get(model.getCashierId()));
                message.setMessage(TimeUtil.getCurrentTime() + "请求【结算】加急处理");
                break;
            default:
                break;
        }
        if (shiroUsers.size() == 0) {
            logger.error("不满足推送条件!");
            return;
        }

        Set<Channel> channelSet = new HashSet();
        shiroUsers.forEach(o -> {
            Set<Channel> channels = NettyCacheUtils.getChannel(o.getId().toString());
            if (!CollectionUtils.isEmpty(channels)) {
                channelSet.addAll(channels);
            }
        });
        pushServiceApi.pushMsg(channelSet, WmsNettyCommands.PUSH_ORDER_CHANGE, message.toString());
        logger.info("===采购单【{}】加急处理通知===END===", model.getNo());
    }

    private List<ShiroUser> filterBySalesman(Long salesmanId, List<ShiroUser> shiroUsers) {
        List<ShiroUser> lst = new ArrayList<>();
        if (!CollectionUtils.isEmpty(shiroUsers)) {
            shiroUsers.forEach(o -> {
                if (StringUtils.isEmpty(o.getControlUsers())) {
                    lst.add(o);
                } else {
                    List<String> ids = Arrays.asList(o.getControlUsers().split(","));
                    if (ids.contains(salesmanId.toString())) {
                        lst.add(o);
                    }
                }
            });
        }
        return lst;
    }

    private void dealPush(OrderInfo orderInfo, OrderProcess orderProcess, String msg, NettyOrderMessage message) {
        Set<Channel> channelSet = new HashSet();

        // 推送给超级管理员
        List<ShiroUser> supers = CollectionCache.dutyEmployees.get(1L);
        if (!CollectionUtils.isEmpty(supers)) {
            supers.forEach(superUser -> {
                Set<Channel> channels = NettyCacheUtils.getChannel(superUser.getId().toString());
                if (!CollectionUtils.isEmpty(channels)) {
                    channelSet.addAll(channels);
                }
            });
        }
        // 推送给业务员
        Set<Channel> salesmanChannelSet = NettyCacheUtils.getChannel(String.valueOf(orderInfo.getSalesmanId()));
        if (!CollectionUtils.isEmpty(salesmanChannelSet)) {
            channelSet.addAll(salesmanChannelSet);
        }
        // 极光推送给业务员
        JPushSendDto sendDtoSalesman = new JPushSendDto();
        sendDtoSalesman.setTitle(orderProcess.getName());
        sendDtoSalesman.setContent(msg);
        sendDtoSalesman.setPushConditions(Collections.singletonList(orderInfo.getSalesmanId().toString()));
        jPushUtil.sendPushWithCallback(jPushProperties.getPurchase(), sendDtoSalesman);
        // 写入消息
        messageService.save(new Message(orderInfo.getSalesmanId(), "采购单号：" + orderInfo.getNo(), msg));

        // 推送给采购主管
        List<ShiroUser> leads = CollectionCache.dutyEmployees.get(wmsProperties.getPurchase().getDutyId().get(0));
        if (!CollectionUtils.isEmpty(leads)) {
            leads.forEach(lead -> {
                Set<Channel> leadChannelSet = NettyCacheUtils.getChannel(lead.getId().toString());
                if (!CollectionUtils.isEmpty(leadChannelSet)) {
                    channelSet.addAll(leadChannelSet);
                }
            });
        }
        // 发货通知至接货员
        if (message.getStatus().equals(SupOrderAction.CHECKING)) {
            Set<Channel> consigneeChannelSet = NettyCacheUtils.getChannel(String.valueOf(orderInfo.getConsigneeId()));
            if (!CollectionUtils.isEmpty(consigneeChannelSet)) {
                channelSet.addAll(consigneeChannelSet);
            }
        }
        // 极光推送给接货员
        if (message.getStatus().equals(SupOrderAction.CHECKING) || message.getStatus().equals(SupOrderAction.ECEIVING) ||
                message.getStatus().equals(SupOrderAction.RETURNING)) {
            JPushSendDto sendDtoConsignee = new JPushSendDto();
            sendDtoConsignee.setTitle(orderProcess.getName());
            sendDtoConsignee.setContent(msg);
            sendDtoConsignee.setPushConditions(Collections.singletonList(orderInfo.getConsigneeId().toString()));
            jPushUtil.sendPushWithCallback(jPushProperties.getReceiving(), sendDtoConsignee);
            // 写入消息
            messageService.save(new Message(orderInfo.getConsigneeId(), "采购单号：" + orderInfo.getNo(), msg));
        }
        // 定价发送至财务主管
        if (message.getStatus().equals(SupOrderAction.PRICING)) {
            List<ShiroUser> finLeads = CollectionCache.dutyEmployees.get(wmsProperties.getPurchase().getDutyId().get(0));
            finLeads.forEach(lead -> {
                Set<Channel> leadChannelSet = NettyCacheUtils.getChannel(lead.getId().toString());
                if (!CollectionUtils.isEmpty(leadChannelSet)) {
                    channelSet.addAll(leadChannelSet);
                }
            });
        }
        // 核算 发送至出纳
        if (message.getStatus().equals(SupOrderAction.PRICING)) {
            Set<Channel> cashierChannelSet = NettyCacheUtils.getChannel(String.valueOf(orderInfo.getCashierId()));
            if (!CollectionUtils.isEmpty(cashierChannelSet)) {
                channelSet.addAll(cashierChannelSet);
            }
        }
        // 发送至供应商
        Set<Channel> supplierChannelSet = NettyCacheUtils.getChannel(String.valueOf(WmsNettyCommands.SUPPLIER_PREFIX + orderInfo.getSupplierId()));
        if (!CollectionUtils.isEmpty(supplierChannelSet)) {
            channelSet.addAll(supplierChannelSet);
        }
        // 极光推送
        // 极光推送给供应商
        JPushSendDto sendDtoConsignee = new JPushSendDto();
        sendDtoConsignee.setTitle(orderProcess.getName());
        sendDtoConsignee.setContent(msg);
        sendDtoConsignee.setPushConditions(Collections.singletonList(orderInfo.getSupplierId().toString()));
        jPushUtil.sendPushWithCallback(jPushProperties.getSupplier(), sendDtoConsignee);
        // 写入消息
        messageService.save(new Message(orderInfo.getSupplierId(), "采购单号：" + orderInfo.getNo(), msg));

        if (!CollectionUtils.isEmpty(channelSet)) {
            pushServiceApi.pushMsg(channelSet, WmsNettyCommands.PUSH_ORDER_CHANGE, message.toString());
            pushServiceApi.pushMsg(channelSet, WmsNettyCommands.PUSH_PUR_ORDER, JSON.toJSONString(orderInfo));
        }

    }

}

